<template>
  <a-form-model-item :label="label" :prop="prop" :rules="fnRules()">
    <a-input
      v-if="readonly"
      v-model="form[prop]"
      :placeholder="placeholder"
      disabled
      style="background-color: #fff; color: rgba(0, 0, 0, 0.65); cursor: auto"
      :prefix="prefix"
      :suffix="suffix"
    >
    </a-input>
    <a-upload v-else name="file" :customRequest="customRequest" :accept="accept" :fileList="null">
      <a-button :disabled="isOccupied" :loading="isOccupied"> <a-icon type="upload" /> 点击上传 </a-button>
    </a-upload>
    <div>
      <!-- <p v-show="form[prop].length === 0" class="tips">暂无上传文件</p>
      <div v-for="(item, index) in form[prop]" :key="index">
        <img class="imgBox" :src="'http://localhost:9999' + item.url" />
        <Button type="stop" label="删除" @click="del(index)"></Button>
      </div> -->
      <p v-show="!form.url" class="tips">暂无上传文件</p>
      <div v-if="form.url" class="Row">
        <img class="imgBox" :src="IMGURL + form.url" />
        <!-- <img class="imgBox" :src="getImgUrl(form[prop].url)" /> -->
        <Button type="stop" label="删除" @click="delObj"></Button>
      </div>
    </div>
    <!-- </a-list> -->
  </a-form-model-item>
</template>

<script>
import axios from 'axios';
import { uploadFile } from '@/api/user';
import Button from '@/components/typicalControl/button';
export default {
  name: 'ResealUpload',
  components: {
    Button: Button,
  },
  props: {
    // 绑定的对象
    form: {
      type: Object,
      default: () => {
        return {};
      },
    },
    // 绑定对象的属性
    prop: {
      type: String,
      default: 'url',
    },
    // 文字
    label: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请输入',
    },
    // 禁止操作
    disabled: {
      type: Boolean,
      default: false,
    },
    // 只读
    readonly: {
      type: Boolean,
      default: false,
    },
    // 输入框前部内容
    prefix: {
      type: String,
      default: '',
    },
    // 输入框后部内容
    suffix: {
      type: String,
      default: '',
    },
    // 可上传的文件类型
    accept: {
      type: String,
      // default: '.jpg, .jpeg, .png'
      default: '.jpg, .jpeg, .png',
    },
    maxMB: {
      type: Number,
      default: 2,
    },
    // 默认必填
    isRequired: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    var validatorData = (rule, value, callback) => {
      if (this.form.url) {
        callback();
      } else {
        callback(new Error('请上传图片！'));
      }
    };
    return {
      isOccupied: false,
      validatorData: validatorData,
      // file: []
      IMGURL: '',
    };
  },
  created() {
    this.IMGURL = (location.host == 'zh.dpcpower.com')
      ? 'https://zh.dpcpower.com'
      : 'https://testzh.dpcpower.com';
  },
  methods: {
    /**
     * [fnRules 上传图片校验必填规则]
     * @return {[type]} [description]
     */
    fnRules() {
      if (this.isRequired) {
        return { required: true, validator: this.validatorData, trigger: 'change' };
      } else {
        return null;
      }
    },
    /**
     * [setFileList 设置已创建文件]
     * @param {[type]} val [description]
     */
    setFileList(val) {
      this.form[this.prop] = [];
      if (val) {
        for (var i = 0; i < val.length; i++) {
          this.form[this.prop].push(val[i]);
        }
      }
    },
    /**
     * [mbToB MB转byte]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    mbToB(val) {
      return val * 1024 * 1024;
    },
    /**
     * [customRequest 自定义文件上传]
     * @param  {[type]} upload [组件参数含文件]
     * @return {[type]}        [description]
     */
    customRequest(upload) {
      if (this.isSizeCheck(upload.file.size)) {
        const param = new FormData();
        param.append('file', upload.file);
        // const config = {
        //   headers: { 'Content-Type': 'multipart/form-data' },
        // };
        this.isOccupied = true;
        // axios.post('http://192.168.20.107:8002/api/ChargeTmplController/uploadImage', param, config).then(res => {
        //   this.$set(this.form, this.prop, res.data);
        //   // Object.assign(this.form[this.prop], res.data);
        //   this.form[this.prop].id = '12345';
        //   this.$emit('change', this.form[this.prop]);
        //   this.isOccupied = false;
        // }).catch(() => {
        //   this.$message.error('上传失败了！');
        //   this.isOccupied = false;
        // });
        uploadFile(param)
          .then((res) => {
            // this.$set(this.form, this.prop, res.data);
            // // Object.assign(this.form[this.prop], res.data);
            this.form.url = res.data;
            this.$emit('change', res.data);
            this.isOccupied = false;
            if (res.code != 200) {
              this.$message.error('上传失败了！');
            }
          })
          .catch((err) => {
            console.log(err);
            this.$message.error('上传失败了！');
            this.isOccupied = false;
          });
      } else {
        this.$message.error('上传文件大小超过' + this.maxMB + 'MB！');
      }
    },
    /**
     * [isSizeCheck 校验大小是否符合(允许相等)]
     * @param  {[type]}  size [文件大小]
     * @return {Boolean}      [description]
     */
    isSizeCheck(size) {
      if (this.mbToB(this.maxMB) > size) {
        return true;
      } else {
        return false;
      }
    },
    /**
     * [del 图片删除]
     * @param  {[type]} index [序号]
     * @return {[type]}       [description]
     */
    del(index) {
      this.form[this.prop].splice(index, 1);
      this.$emit('change', this.form[this.prop]);
    },
    delObj() {
      // for (var key in this.form[this.prop]) {
      //   this.form[this.prop][key] = undefined;
      //   delete this.form[this.prop][key];
      // }
      this.form.url = '';
      this.$emit('change', '');
    },
    // 图片路径
    getImgUrl(src) {
      var newSrc = '';
      if (src) {
        // newSrc = process.env.VUE_APP_SRC_FRAGMENT + '/' + src;
        newSrc = process.env.VUE_APP_SRC_FRAGMENT + src;
      }
      return newSrc;
    },
  },
};
</script>
<style scoped>
.Row {
  position: relative;
  overflow: hidden;
  clear: both;
}
.tips {
  color: #d9d9d9;
}
.title {
  float: left;
  width: calc(100% - 50px);
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.imgBox {
  float: left;
  width: 110px;
  max-height: 140px;
}
</style>
